@echo off
REM Change to the script's directory
cd /d "%~dp0"

REM Set console to UTF-8
chcp 65001 > nul
setlocal

REM --- User Configuration ---
REM Set this to the root of your Qt installation directory.
REM Example: C:\Qt\6.8.0\msvc2019_64 or D:\Qt\6.8.0\mingw_64
set "QT_INSTALL_PATH=D:\MySoftwares\QT\6.8.2\mingw_64"

REM Set the CMake generator.
REM Options: "MinGW Makefiles", "Visual Studio 17 2022", etc.
set "CMAKE_GENERATOR=MinGW Makefiles"

REM Set the number of parallel build jobs (leave empty for default).
set "CMAKE_BUILD_PARALLEL_LEVEL=16"
REM --- End of User Configuration ---


if "%QT_INSTALL_PATH%"=="C:\path\to\your\Qt\installation" (
    echo.
    echo 错误: 您需要在此脚本中设置 QT_INSTALL_PATH 变量。
    echo.
    exit /b 1
)

if not exist "%QT_INSTALL_PATH%" (
    echo.
    echo 错误: 指定的 QT_INSTALL_PATH 不存在:
    echo %QT_INSTALL_PATH%
    echo.
    exit /b 1
)

set "BUILD_DIR=build"

if not exist "%BUILD_DIR%" (
    mkdir "%BUILD_DIR%"
)

cd "%BUILD_DIR%"

if not exist "CMakeCache.txt" (
    echo Configuring project for the first time...
    REM Pass Qt path to CMake
    cmake .. -G "%CMAKE_GENERATOR%" -DCMAKE_PREFIX_PATH="%QT_INSTALL_PATH%"
) else (
    echo Project already configured. Skipping CMake configuration.
)

if %errorlevel% neq 0 (
    echo CMake 配置失败。
    exit /b %errorlevel%
)

echo 正在构建项目...
if not "%CMAKE_BUILD_PARALLEL_LEVEL%"=="" (
    echo 使用 %CMAKE_BUILD_PARALLEL_LEVEL% 个线程进行编译。
    cmake --build . --config Release --parallel %CMAKE_BUILD_PARALLEL_LEVEL%
) else (
    echo 使用默认线程数进行编译。
    cmake --build . --config Release
)

if %errorlevel% neq 0 (
    echo 构建失败。
    exit /b %errorlevel%
)

echo.
echo 构建成功!

set "PACKAGE_DIR=%~dp0package"
set "EXECUTABLE_NAME=appPromptCreator.exe"
set "SOURCE_EXECUTABLE=%CD%\%EXECUTABLE_NAME%"
set "DEPLOY_EXECUTABLE=%PACKAGE_DIR%\%EXECUTABLE_NAME%"

if not exist "%SOURCE_EXECUTABLE%" (
    echo 错误: 构建后未找到可执行文件: %SOURCE_EXECUTABLE%
    exit /b 1
)

if not exist "%PACKAGE_DIR%" (
    mkdir "%PACKAGE_DIR%"
)

echo 正在复制可执行文件到部署目录...
copy /Y "%SOURCE_EXECUTABLE%" "%PACKAGE_DIR%" > nul

set "SCRIPT_DIR=%~dp0"
if "%SCRIPT_DIR:~-1%"=="\" set "SCRIPT_DIR=%SCRIPT_DIR:~0,-1%"

echo 正在使用 windeployqt 部署依赖项...
call "%QT_INSTALL_PATH%\bin\windeployqt.exe" --qmldir "%SCRIPT_DIR%" --qmldir "%QT_INSTALL_PATH%\qml" "%DEPLOY_EXECUTABLE%" > windeployqt.log 2>&1

if %errorlevel% neq 0 (
    echo windeployqt 部署失败。请查看 windeployqt.log 获取详细信息。
    type "%~dp0build\windeployqt.log"
    exit /b %errorlevel%
)

echo 部署成功!
echo.
echo 正在启动应用程序...
start "" "%DEPLOY_EXECUTABLE%"
echo 可执行文件和依赖项位于 '%PACKAGE_DIR%' 目录中。

endlocal